class ConsumerInfosController < ApplicationController
  before_action :set_consumer_info, only: %i(show edit update)
  skip_before_action :authenticate_user!, except: %i(index)
  layout 'front', except: %i(index)

  # GET /consumer_infos
  # GET /consumer_infos.json
  def index
    respond_to do |format|
      format.html
      format.json { render json: ConsumerInfosDatatable.new(view_context, current_user) }
    end
  end

  # GET /consumer_infos/1
  # GET /consumer_infos/1.json
  def show
  end

  # GET /consumer_infos/new
  def new
    @consumer_info = ConsumerInfo.new
  end

  # GET /consumer_infos/1/edit
  def edit
  end

  # POST /consumer_infos
  # POST /consumer_infos.json
  def create
    @consumer_info = ConsumerInfo.new(consumer_info_params)
    verfiy_code = Redis.new.get "mobile_#{params[:mobile]}"

    if verfiy_code != params[:verfiy_code]
      render json: { result: 'fail', message: '验证码无效' }
      return
    end

    if @consumer_info.save
      render json: { result: 'success', message: '提交成功！', id: @consumer_info.id }
    else
      render json: { result: 'fail', message: "#{@consumer_info.errors.full_messages.first}" }
    end
  end

  # PATCH/PUT /consumer_infos/1
  # PATCH/PUT /consumer_infos/1.json
  def update
    # respond_to do |format|
    #   if @consumer_info.update(consumer_info_params)
    #     format.js { render_js_for_form @consumer_info, consumer_infos_path, '客户信息新建成功！' }
    #   else
    #     format.html { render :edit }
    #     format.json { render json: @consumer_info.errors, status: :unprocessable_entity }
    #   end
    # end
  end

  # DELETE /consumer_infos/1
  # DELETE /consumer_infos/1.json
  def destroy
    # @consumer_info[:is_delete] = true
    # @consumer_info.save
    # respond_to do |format|
    #   format.js { render_js_for_form @consumer_info, consumer_infos_path, '客户信息已删除！' }
    #   # format.html { redirect_to consumer_infos_url, notice: '客户信息已删除.' }
    #   # format.json { head :no_content }
    # end
  end

  def verfiy_code
    verfiy_code = "#{rand(9)}#{rand(9)}#{rand(9)}#{rand(9)}"
    mobile      = params[:mobile]
    Rails.logger.info "验证码为：#{verfiy_code}"
    
    ChinaSMS.use :yunpian, password: ENV['YUNPIAN_PWD']
    ChinaSMS.to mobile, ENV['YUNPIAN_SMS_PREFIX'] + verfiy_code
    # 发送验证码
    Redis.new.set "mobile_#{mobile}", verfiy_code
    Redis.new.expire "mobile_#{mobile}", 60*10
    render json: { message: '验证码已发送！' }
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_consumer_info
      @consumer_info = ConsumerInfo.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def consumer_info_params
      { name: params[:name], mobile: params[:mobile] }
    end
end
